package views.category;

import org.intellij.lang.annotations.Language;
import tools.Icons;
import utils.DBUtil;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

/*ok*/
public class Category_Update_Delete extends JFrame {
    private JScrollPane jsp = new JScrollPane();
    private JTable table = new JTable();
    private JButton btn_change = new JButton("修改");
    private JButton btn_delete = new JButton("删除");
    private MyModel model;
    private JLabel jL_job_category_id = new JLabel("职业类型编号:");
    private JLabel jl_job_categoryName = new JLabel("职业类型名称：");
    private JTextField jT_jobCategory_id = new JTextField();//编号
    private JTextField jT_jobCategory = new JTextField();
    private JButton btn_find = new JButton("查找");
    private JTextField jT_find = new JTextField();
    private Panel panBtn = new Panel();
    private Panel panLab = new Panel();
    Icons icons = new Icons();
    ImageIcon imageIcon = new ImageIcon("src/images/job_category.png");

    public Category_Update_Delete() {
        this.setSize(600, 500);
        setIconImage(imageIcon.getImage().getScaledInstance(80, 80, Image.SCALE_DEFAULT));
        setTitle("职业类型信息修改与删除");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        model = new MyModel("select * from job_category");
        table.setModel(model);
        // 修改列名称
        table.getColumnModel().getColumn(0).setHeaderValue("编号");
        table.getColumnModel().getColumn(1).setHeaderValue("类型名称");
        DefaultTableCellRenderer r = new DefaultTableCellRenderer();
        r.setHorizontalAlignment(JLabel.CENTER);
        table.setDefaultRenderer(Object.class, r);
        // 设置可见视图的接口
        jsp.setViewportView(table);
        // 定义表格 宽600，高度200
        jsp.setPreferredSize(new Dimension(600, 300));
        // 设置横向和垂直滚动条可见
        jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        panBtn.add(btn_change);
        panBtn.add(btn_delete);
        // 设置中间的panel布局为空
        panLab.setLayout(null);

        // 给组件设置位置
        jT_find.setSize(140, 30);
        jT_find.setLocation(180, 20);

        btn_find.setSize(80, 30);
        btn_find.setLocation(325, 20);

        jL_job_category_id.setSize(100, 30);
        jL_job_category_id.setLocation(20, 60);
        jL_job_category_id.setHorizontalAlignment(JLabel.RIGHT);
        jT_jobCategory_id.setSize(150, 30);
        jT_jobCategory_id.setLocation(120, 60);

        jl_job_categoryName.setSize(100, 30);
        jl_job_categoryName.setLocation(280, 60);
        jl_job_categoryName.setHorizontalAlignment(JLabel.RIGHT);
        jT_jobCategory.setSize(150, 30);
        jT_jobCategory.setLocation(380, 60);


        // 把标签和文本框加到panLab面板中
        panLab.add(jL_job_category_id);
        panLab.add(jT_jobCategory_id);

        panLab.add(jl_job_categoryName);
        panLab.add(jT_jobCategory);

        panLab.add(jT_find);
        panLab.add(btn_find);

        this.add(jsp, BorderLayout.NORTH);
        this.add(panLab, BorderLayout.CENTER);
        this.add(panBtn, BorderLayout.SOUTH);

        jT_jobCategory_id.setEditable(false);
        // 获取表里的值
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                String cateId, name;
                int id;
                int selRow = table.getSelectedRow();
                cateId = table.getValueAt(selRow, 0).toString().trim();
                id = Integer.parseInt(cateId);
                name = table.getValueAt(selRow, 1).toString().trim();
                jT_jobCategory_id.setText(cateId);
                jT_jobCategory.setText(name);
            }
        });

        btn_find.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                String s = jT_find.getText().trim();
                @Language("MySQL")
                String sql = "select * from job_category where category_name like " +
                        "'%" + s + "%'";
                model = new MyModel(sql);
                table.setModel(model);
                table.getColumnModel().getColumn(0).setHeaderValue("编号");
                table.getColumnModel().getColumn(1).setHeaderValue("类型名称");
                DefaultTableCellRenderer r = new DefaultTableCellRenderer();
                r.setHorizontalAlignment(JLabel.CENTER);
                table.setDefaultRenderer(Object.class, r);

            }
        });

        btn_change.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                String categoryname = jT_jobCategory.getText().trim();
                int id = Integer.parseInt(jT_jobCategory_id.getText().trim());
                Statement stmt = DBUtil.getStatement();
                String sql = "update job_category set category_name = '"
                        + categoryname
                        + "'"
                        + "where category_id="
                        + id
                        + ";";
                try {
                    stmt.executeUpdate(sql);
                    JOptionPane.showMessageDialog(null, "修改成功。", "成功", JOptionPane.INFORMATION_MESSAGE, icons.getOkImage());
                    jT_jobCategory_id.setText("");
                    jT_jobCategory.setText("");
                    // 实时更新表
                    @Language("MySQL")
                    String updateSQL = "SELECT * from job_category";
                    model.fireTableDataChanged();
                    model = new MyModel(updateSQL);
                    table.setModel(model);
                    table.getColumnModel().getColumn(0).setHeaderValue("编号");
                    table.getColumnModel().getColumn(1).setHeaderValue("类型名称");
                    DefaultTableCellRenderer r = new DefaultTableCellRenderer();
                    r.setHorizontalAlignment(JLabel.CENTER);
                    table.setDefaultRenderer(Object.class, r);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });

        btn_delete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                int i = Integer.parseInt(jT_jobCategory_id.getText().trim());
                int result = JOptionPane.showConfirmDialog(null, "确定删除吗?", "提示", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, icons.getQuestionImage());
                if (result == JOptionPane.YES_OPTION) {
                    Statement stmt = DBUtil.getStatement();
                    @Language("MySQL")
                    String sql3 = "select job_id from job_info where category_id=" + i;
                    String sql = "delete from job_category where category_id = " + i + ";";

                    try {
                        ResultSet rs = stmt.executeQuery(sql3);
                        if (!rs.next()) {
                            stmt.executeUpdate(sql);
                            JOptionPane.showMessageDialog(null, "已删除！", "成功", JOptionPane.INFORMATION_MESSAGE, icons.getOkImage());
                            // 实时更新表格数据
                            @Language("MySQL")
                            String sql2 = "SELECT * from job_category";
                            model = new MyModel(sql2);
                            table.setModel(model);
                            table.getColumnModel().getColumn(0).setHeaderValue("编号");
                            table.getColumnModel().getColumn(1).setHeaderValue("类型名称");
                        } else {
                            JOptionPane.showMessageDialog(null, "有职业是此职业类型，无法删除", "错误", JOptionPane.ERROR_MESSAGE, icons.getErrorImage());
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                } else {
                    dispose();
                }
            }
        });
    }

    class MyModel extends AbstractTableModel {
        private int row;
        private int column;
        private ResultSet rs;
        private Statement stmt;

        public MyModel(@Language("MySQL") String sql) {
            stmt = DBUtil.getStatement();
            try {
                rs = stmt.executeQuery(sql);
                rs.last();// 将光标移到最后一行
                row = rs.getRow();// 获取行号(最大行索引)
                ResultSetMetaData rsmd = rs.getMetaData();// 通过结果集对象来获取
                column = rsmd.getColumnCount();// 获取列数
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public int getColumnCount() {
            return column;
        }

        @Override
        public int getRowCount() {
            return row;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object value = null;
            try {
                rs.absolute(rowIndex + 1);
                value = rs.getString(columnIndex + 1);// 获取表里的数据
            } catch (Exception e) {
                e.printStackTrace();
            }
            return value;
        }
    }
}
